import {routing} from "../../utils/routing";

const shareLocationKey = "share_location"
Page({
    data: {
        shareLocation: false,
        avatarUrl: '',
    },

    // async onLoad(option) {
    //     console.log('unlocking car', option.car_id)
    //     const userInfo = await getApp<IAppOption>().globalData.userInfo
    //     this.setData({
    //         avatarUrl: userInfo.avatarUrl,
    //         shareLocation: wx.getStorageSync(shareLocationKey) || false,
    //     })
    // },
    async onLoad(option: Record<'car_id', string>) {
        const o: routing.LockOpts = option
        console.log('unlocking car', o.car_id)
        const userInfo = await getApp<IAppOption>().globalData.userInfo
        this.setData({
            avatarUrl: userInfo.avatarUrl,
            shareLocation: wx.getStorageSync(shareLocationKey) || false,
        })
    },

    onGetUserInfo(e: any) {
        const userInfo: WechatMiniprogram.UserInfo = e.detail.userInfo
        if (userInfo) {
            getApp<IAppOption>().resolveUserInfo(userInfo)
        }
    },

    onShareLocation(e: any) {
        const shareLocation: boolean = e.detail.value
        wx.setStorageSync(shareLocationKey, shareLocation)
    },

    onUnlockTap() {
        wx.getLocation({
            type: 'gcj02',
            success: loc => {
                console.log('starting a trip', {
                    location: {
                        latitude: loc.latitude,
                        longitude: loc.longitude
                    },
                    // todo 需要双向绑定
                    avatarUrl: this.data.shareLocation ? this.data.avatarUrl : '',
                })
                const tripID = 'trip456'

                wx.showLoading({
                    title:'开锁中',
                    mask:true
                })
                setTimeout(() => {
                    wx.redirectTo({
                        //url: `/pages/driving/driving?trip_id=${tripID}`,
                        url: routing.drving({
                            trip_id: tripID
                        }),
                        complete: () =>{
                            wx.hideLoading()
                        }
                    })
                }, 2000)
            },
            fail: () => {
                wx.showToast({
                    icon: 'none',
                    title: '请前往设置页授权位置信息'
                })
            }
        })
    }
})
